<?php
class Mwc_SystemPoint_Model_Sales_Quote_Address_Total_Discount extends Mage_Sales_Model_Quote_Address_Total_Abstract{
    protected $_code = 'discount';
    static protected $discountvalue = 0;
    static protected $discountper = 0;
 
    public function collect(Mage_Sales_Model_Quote_Address $address)
    {
        parent::collect($address);
 
        $this->_setAmount(0);
        $this->_setBaseAmount(0);
 
        $quote = $address->getQuote();
        
    	    
        $items = $this->_getAddressItems($address);
        if (!count($items)) {
            return $this; //this makes only address type shipping to come through
        }
 
 
 		//check if logged in or not
 		$per = 0;
 		if(Mage::helper('customer')->isLoggedIn()){	     
// 			get value of discount
 			$email = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
 			$point = Mage::getModel('systempoint/userpoint');
 			$memship = Mage::getModel('systempoint/membership');
 			$vip = Mage::getModel('systempoint/viplist');
			$userpoint = $point->loadByEmail($email);
			if($userpoint[userpoint]!=''){
				$disrow = $memship->loadByPoint($userpoint['userpoint']);
				$per = $disrow['percent_discount'];
	//			print_r($disrow);die;
			    $value = $disrow['percent_discount']/100;    
			    if($vip->checkVip($email) && $value < 0.1){
			    	$tmp = 0.1;
			    	if($tmp>$value){
			    		$value = $tmp;
			    	}
			    }
			    $orgGrand = $address->getGrandTotal();
	        	$discount = $orgGrand*$value;
	        	$this->discountper = $disrow['percent_discount'];
	        	$grand = $orgGrand - $discount;
	        	
				$address->setDiscountAmount($discount);
				$address->setSubtotalWithDiscount($discount);
				$address->setBaseDiscountAmount($discount);
				$address->setBaseSubtotalWithDiscount($discount);
	
		        $address->setGrandTotal($grand);
		        $address->setBaseGrandTotal($grand);      
			}
 		}
		Mage::getSingleton('core/session')->setPerDis($per);
       	return $this;
    }
    
    public function fetch(Mage_Sales_Model_Quote_Address $address)
    {   	
		$myData = Mage::getSingleton('core/session')->getPerDis();
    	$address->addTotal(array(
                'code'=>$this->getCode(),
                'title'=>'</td><td style="text-align: right;"><strong>'.Mage::helper('sales')->__('Discount').' ('.$myData.'%)</strong>',
                'value'=> $address->getDiscountAmount(),
        ));
        return $this;
    }
}